package com.zhang.util;

import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.record.*;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class GeoIPDataFetcher {
    public static void main(String[] args) {


        final List<String> strings = new ArrayList<>();
        strings.add("119.49.148.100");
        strings.add("120.41.168.200");
        strings.add("117.29.180.80");
        strings.add("119.0.150.30");
        strings.add("119.134.120.60");
        strings.add("118.50.170.90");
        strings.add("117.35.145.70");
        strings.add("116.25.165.10");
        for (String string : strings) {

            try {
                System.out.println("==============================================");
                // 加载 GeoIP2 数据库文件，替换为实际路径
                File database = new File("D:\\迅雷下载\\GeoLite2-City_20250318\\GeoLite2-City_20250318\\GeoLite2-City.mmdb");
                DatabaseReader reader = new DatabaseReader.Builder(database).build();

                // 要查询的 IP 地址
                InetAddress ipAddress = InetAddress.getByName(string);

                // 查询 IP 地址的地理信息
                CityResponse response = reader.city(ipAddress);

                // 获取国家信息
                Country country = response.getCountry();
                System.out.println("国家: " + country.getName());

                // 获取细分区域信息
                Subdivision subdivision = response.getMostSpecificSubdivision();
                if (subdivision != null) {
                    System.out.println("细分区域: " + subdivision.getName());
                }

                // 获取城市信息
                City city = response.getCity();
                if (city != null) {
                    System.out.println("城市: " + city.getName());
                }

                // 获取经纬度信息
                Location location = response.getLocation();
                if (location != null) {
                    System.out.println("纬度: " + location.getLatitude());
                    System.out.println("经度: " + location.getLongitude());
                }

            } catch (IOException e) {
                System.err.println("读取 GeoIP2 数据库时出错: " + e.getMessage());
            } catch (com.maxmind.geoip2.exception.GeoIp2Exception e) {
                System.err.println("查询 IP 地址信息时出错: " + e.getMessage());
            }
        }
    }
}